<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          type="text"
          prefix-icon="el-icon-search"
          placeholder="输入员工姓名全员搜索"
          @input="onNameChange"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="tree"
          highlight-current
          :data="deptList"
          node-key="id"
          :props="defaultProps"
          default-expand-all
          :expand-on-click-node="false"
          @current-change="onNodeChange"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/employee/details')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="employeeList">
          <el-table-column label="头像" width="100px">
            <template v-slot="{row}">
              <el-avatar v-if="row.staffPhoto" size="medium" :src="row.staffPhoto" />
              <span v-else class="username"> {{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="手机号" prop="mobile" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式" prop="formOfEmployment" align="center">
            <template v-slot="{row}">
              {{ row.formOfEmployment === 1 ? '正式' : row.formOfEmployment === 2 ? '实习' : '无' }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" width="150px">
            <template v-slot="{ row }">
              <el-button type="text" size="mini" @click="$router.push(`/employee/details/${row.id}`)">编辑</el-button>
              <el-button type="text" size="mini" style="padding-right: 10px;" @click="assignRole(row.id)">角色</el-button>
              <el-popconfirm title="确定删除吗？" @onConfirm="deleteEmployee(row)">
                <el-button slot="reference" size="small" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="padding-top: 10px;" type="flex" justify="end">
          <el-pagination
            layout="total, prev, pager, next, sizes"
            :total="total"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            :page-sizes="[5, 10, 20]"
            @size-change="onSizeChange"
            @current-change="onCurrentChange"
          />
        </el-row>
      </div>
      <!-- 导入excel对话框 -->
      <import-excel :show-excel-dialog.sync="showExcelDialog" @downloadTemplate="downloadTemplate" @uploadExcel="uploadExcel" />
      <!-- 角色对话框 -->
      <el-dialog v-loading="roleLoading" title="角色" :visible.sync="showRoleDialog">
        <el-checkbox-group v-model="roleIds">
          <el-checkbox v-for="item in roles" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
        </el-checkbox-group>
        <el-row slot="footer" type="flex" justify="center">
          <el-button type="primary" size="small" @click="assignRoleComfirm">确定</el-button>
          <el-button size="small" @click="showRoleDialog = false">取消</el-button>
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getDepartmentList } from '@/api/department'
import { getRolesEnable } from '@/api/role'
import { getEmployeeList, exportExcel, downloadTemplate, uploadExcel, deleteEmployee, getEmployee, assignRole } from '@/api/employee'
import FileSaver from 'file-saver'
import ImportExcel from '@/components/import-excel.vue'
import { transList2Tree } from '@/utils/date-handle'

export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      // 部门列表
      deptList: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 员工列表
      employeeList: [],
      // 查询员工的参数列表
      queryParams: {
        departmentId: '',
        page: 1, // 当前页
        pagesize: 10, // 每页显示数
        keyword: '' // 模糊搜索关键字
      },
      total: 999, // 员工总数
      showExcelDialog: false, // 上传excel文件对话框
      showRoleDialog: false, // 角色对话框
      // 员工的角色列表
      roles: [],
      // 员工角色id列表
      roleIds: [],
      // 选中的员工id
      id: '',
      roleLoading: false
    }
  },
  created() {
    this.getDeptList()
  },
  methods: {
    // 获取部门列表
    async getDeptList() {
      const res = await getDepartmentList()
      // 将后端返回的列表改成树结构
      this.deptList = transList2Tree(res)
      this.queryParams.departmentId = 1
      this.getEmployeeList()
      this.$nextTick(() => {
        this.$refs.tree.setCurrentKey(1)
      })
    },

    // 获取员工列表
    async getEmployeeList() {
      const res = await getEmployeeList(this.queryParams)
      this.employeeList = res.rows
      this.total = res.total
    },

    // 树形节点被选中时
    onNodeChange(data) {
      // 当用户重复点击时不处理
      if (this.queryParams.departmentId !== data.id) {
        this.queryParams.departmentId = data.id
        this.getEmployeeList()
      }
    },
    // 每页显示数改变
    onSizeChange(pagesize) {
      this.queryParams.pagesize = pagesize
      this.queryParams.page = 1
      this.getEmployeeList()
    },
    // 当前页码改变
    onCurrentChange(page) {
      this.queryParams.page = page
      this.getEmployeeList()
    },

    // 搜索输入框值改变时
    onNameChange() {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.getEmployeeList()
      }, 5000) // 延时一秒
    },

    // 导出excel
    async exportExcel() {
      const blobData = await exportExcel()
      FileSaver.saveAs(blobData, '员工信息表.xlsx')
    },

    // 导入excel模板
    async downloadTemplate() {
      const blobdata = await downloadTemplate()
      FileSaver.saveAs(blobdata, '员工导入模板.xlsx')
    },

    // 上传excel
    async uploadExcel(files) {
      if (files.length > 0) {
        // 封装formData上传文件给后端（axios会自动设置content-type为multipart/form-data）
        const formData = new FormData()
        formData.append('file', files[0])
        await uploadExcel(formData)
        // 上传成功后关闭对话框、重载数据
        this.getEmployeeList()
        this.showExcelDialog = false
      }
    },

    // 删除员工
    async deleteEmployee(row) {
      // 当前页不为第一页且当前页只有一个元素是，当前页-1
      if (this.queryParams.page > 1 && this.employeeList.length === 1) this.queryParams.page--
      await deleteEmployee(row.id)
      this.$message.success('删除成功')
      this.getEmployeeList()
    },

    // 弹出分配权限对话框
    async assignRole(id) {
      // 开启加载效果
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      try {
        this.id = id
        // 获取可分配的角色列表
        this.roles = await getRolesEnable()
        // 回显员工原本拥有的角色
        const { roleIds } = await getEmployee(id)
        this.roleIds = roleIds
        // 关闭加载效果，弹出层
        this.showRoleDialog = true
      } finally {
        // 防止出现异常一直在加载
        loading.close()
      }
    },

    // 分配权限确定按钮
    async assignRoleComfirm() {
      if (this.roleIds.length > 0) {
        await assignRole({ id: this.id, roleIds: this.roleIds })
        this.$message.success('分配角色成功')
        this.showRoleDialog = false
      } else {
        this.$message.error('请至少选择一个角色')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
